package net.tp.io;

import java.io.Closeable;
import java.io.IOException;
import java.io.OutputStream;

public class BitOutputStream implements Closeable {

	private final OutputStream outputStream;
	private int buffer;
	private int n;
	
	public BitOutputStream(OutputStream outputStream) {
		this.outputStream = outputStream;
	}
	
	public void write(boolean bit) throws IOException {
		
		buffer >>>= 1;
		if (bit) buffer |= 0b10000000;
		n++;
		
		if (n == 8) {
			outputStream.write(buffer);
			n = 0;
			buffer = 0;
		}
		
	}
	
	public void close() throws IOException {
		if (n > 0) {
			while (n < 8) {
				buffer >>>= 1;
				n++;
			}
			n = 0;
			outputStream.write(buffer);
		}
		outputStream.close();
	}
	
}
